import { sha256 } from 'js-sha256';
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';

import { TIANGONG_USER } from '@/_mock/assets';
import { tgUserRegister, TgUserRegisterReq } from '@/api/services/userService';

import { mockVerificationCodes, mockCompanies } from '../data/mockData';

export interface UserInfo {
  email: string;
  companyName: string;
  companyWebsite: string;
  positionRole: string;
  loginTime: string;
}

export const useRegistration = (onLoginSuccess?: () => void) => {
  const navigate = useNavigate();
  const [currentStep, setCurrentStep] = useState(1);
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [companyName, setCompanyName] = useState('');
  const [companyWebsite, setCompanyWebsite] = useState('');
  const [positionRole, setPositionRole] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [showSuccessModal, setShowSuccessModal] = useState(false);

  const handlePrev = () => {
    setCurrentStep((prev) => prev - 1);
  };

  // 验证邮箱
  const handleEmailVerification = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');

    // 密码验证
    if (password !== confirmPassword) {
      setError('两次输入的密码不一致');
      setIsLoading(false);
      return;
    }

    const passwordRegex =
      /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]).{7,}$/;
    if (!passwordRegex.test(password)) {
      setError('密码必须大于6位，且包含数字、大小写字母和特殊符号');
      setIsLoading(false);
      return;
    }

    // 模拟邮箱验证
    setTimeout(() => {
      if (mockVerificationCodes[email]) {
        setIsLoading(false);
        setCurrentStep(2);
        // 自动填充企业信息
        const emailDomain = email.split('@')[1];
        const company = mockCompanies.find((c) => {
          const domain = c.website.replace('https://www.', '').replace('.com', '');
          return emailDomain.includes(domain) || domain.includes(emailDomain.split('.')[0]);
        });
        if (company) {
          setCompanyName(company.name);
          setCompanyWebsite(company.website);
          setPositionRole(company.role);
        }
      } else {
        // setError('邮箱验证失败，请检查邮箱地址');
        setIsLoading(false);
        setCompanyName('');
        setCompanyWebsite('');
        setPositionRole('');
        setCurrentStep(2);

      }
    }, 1000);
  };

  // 提交企业信息
  const handleCompanyInfoSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError('');

     // 处理注册提交的信息
    const params: TgUserRegisterReq = {
      name: email,
      user_id: email,
      group_name: companyName,
      group_url: companyWebsite,
      password: sha256(password),
      // rolecode: positionRole,
      email,
    };
    try { 
      await tgUserRegister(params);
      // 创建完整的天工用户信息，包含角色权限
      // const tiangongUserInfo = {
      //   ...TIANGONG_USER,
      //   // 覆盖注册信息
      //   email,
      //   name: `${companyName} - ${positionRole}`,
      //   // 添加注册时的企业信息
      //   registrationInfo: {
      //     email,
      //     companyName,
      //     companyWebsite,
      //     positionRole,
      //     loginTime: new Date().toISOString(),
      //   },
      //   // 确保包含天工角色的权限信息
      //   dataVisibility: TIANGONG_USER.dataVisibility,
      //   featurePermissions: TIANGONG_USER.featurePermissions,
      // };

      // // 存储完整的天工用户信息到localStorage
      // localStorage.setItem('tiangong_user', JSON.stringify(tiangongUserInfo));

      // // 同时存储到主系统的用户存储中，使天工用户能够访问worklayouts工作台页面
      // // localStorage.setItem('user', JSON.stringify(tiangongUserInfo));
      // localStorage.setItem(
      //   'token',
      //   JSON.stringify({
      //     accessToken: `tiangong-token-${Date.now()}`,
      //     refreshToken: `tiangong-refresh-token-${Date.now()}`,
      //   }),
      // );

      setIsLoading(false);
      setShowSuccessModal(true);
    } catch (apiError) {
      setError(apiError.message || '注册失败，请稍后重试');
      setIsLoading(false);
    }
  };

  // 处理注册成功确认
  const handleSuccessConfirm = () => {
    setShowSuccessModal(false);
    setCurrentStep(3);

    // 3秒后跳转到工作台页面
    setTimeout(() => {
      onLoginSuccess?.();
      // 跳转到worklayouts工作台页面（图片中显示的页面）
      // navigate('/worklayouts');
      // 保留原有跳转到tiangong-ai的功能注释：
      // navigate('/tiangong-ai');
      navigate('/login');
    }, 3000);
  };

  // 重新开始注册
  const handleRestart = () => {
    setCurrentStep(1);
    setEmail('');
    setPassword('');
    setConfirmPassword('');
    setVerificationCode('');
    setCompanyName('');
    setCompanyWebsite('');
    setPositionRole('');
    setError('');
    setShowSuccessModal(false);
  };

  return {
    // 状态
    currentStep,
    email,
    password,
    confirmPassword,
    verificationCode,
    companyName,
    companyWebsite,
    positionRole,
    isLoading,
    error,
    showSuccessModal,

    // 状态更新函数
    setEmail,
    setPassword,
    setConfirmPassword,
    setVerificationCode,
    setCompanyName,
    setCompanyWebsite,
    setPositionRole,
    setError,

    // 事件处理函数
    handleEmailVerification,
    handleCompanyInfoSubmit,
    handleSuccessConfirm,
    handleRestart,
    handlePrev,
  };
};
